const express=require('express');
const {randomCode,sendCode}=require("./getMessage");
const multer  = require('multer')
const fs  = require('fs')
const pool=require('../pool.js');
//创建路由器对象
const r=express.Router();
//1.用户注册(post /register)
//http://127.0.0.1:8888/v1/users
r.post('/register',(req,res,next)=>{
	//1.1获取数据
	let obj=req.body;
	console.log(obj);
	//1.2执行sql命令
	pool.query('insert into ljk_user set ?',[obj],(err,result)=>{
		if(err){
			//出现错误交给下一个中间件
			next(err);
			return;
		}
		console.log(result);
        res.send({code:200,msg:'注册成功'});
	});
});

//2.用户登录(post /login)
//http://127.0.0.1:8888/v1/users
r.post('/login',(req,res,next)=>{
	//2.1获取传递的数据
	let obj=req.body;
	console.log(obj);
	//2.2执行sql命令
	pool.query('select * from ljk_user where phone=? and upwd=?',[obj.phone,obj.upwd],(err,result)=>{
		if(err){
			next(err);
			return;
		}
		console.log(result);
		//结果是数组，如果数组长度为0说明登录失败
		if(result.length===0){
			res.send({code:201,msg:'登录失败'});
		}else{
			res.send({code:200,msg:'登录成功',data:result});
		}
	});
});

//3.用户重置密码(post /setupwd)
r.put('/setupwd',(req,res,next)=>{
	//2.1获取传递的数据
	let obj=req.body;
	console.log(obj);
	//2.2执行sql命令
	pool.query("update ljk_user set ? where phone=?",[obj,obj.phone],(err,result)=>{
		if(err){
			next(err);
			return;
		}
		console.log(result);
		//结果是对象，如果对象下的属性affectedRows为0说明修改失败
		if(result.affectedRows===0){
			res.send({code:201,msg:'修改失败'});
		}else{
			res.send({code:200,msg:'修改成功',data:result});
		}
	});
});

//4.用户修改(put /edit)
//http://127.0.0.1:8888/v1/users
r.put('/edit',(req,res,next)=>{
	//4.1获取传递的数据
	let obj=req.body;
	console.log(obj);
	//4.3执行sql命令
	pool.query("update ljk_user set ? where uid=?",[obj,obj.uid],(err,result)=>{
		if(err){
			next(err);
			return;
		}
		console.log(result);
		//结果是对象，如果对象下的属性affectedRows为0说明修改失败
		if(result.affectedRows===0){
			res.send({code:201,msg:'修改失败'});
		}else{
			res.send({code:200,msg:'修改成功',data:result});
		}
	});
});

//5.根本用户id查找用户信息
r.get('/count/:uid',(req,res,next)=>{
	let obj=req.params;
	pool.query(`select * from ljk_user where uid=${obj.uid}`,(err,result)=>{
		if(err){
			next(err);
			return;
		}
		console.log(result);
		//结果是对象，如果对象下的属性length为0说明修改失败
		if(result.length===0){
			res.send({code:201,msg:'查询失败'});
		}else{
			res.send({code:200,msg:'查询成功',data:result});
		}
	});
})


//上传图片
const createFolder = function(folder){
    try {
        fs.accessSync(folder)
    } catch(e) {
        fs.mkdirSync(folder)
    }
}
const uploadFolder = './upload/'
createFolder(uploadFolder)
// 通过 filename 属性定制
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, uploadFolder) // 保存的路径
    },
    filename: function (req, file, cb) {
		console.log(file.originalname);
        // 将保存文件名设置为 字段名 + 时间戳 + 后缀名
        let fileFormat = (file.originalname).split('.');
		console.log()
        cb(null, file.fieldname + '-' + Date.now()+ '.' + fileFormat[fileFormat.length - 1]) 

		console.log(fileFormat);
	}
	})
const upload = multer({ storage: storage })
r.post('/upload', upload.single('avatar'), function (req, res, next) {
    const file = req.file
	console.log('文件类型：%s', file.mimetype)
    console.log('原始文件名：%s', file.filename)
    console.log('文件大小：%s', file.size)
    console.log('文件保存路径：%s', file.path)
	let obj=req.body;
	pool.query('update ljk_user set avatar=? where uid=?',[file.filename,obj.uid],(err,result)=>{
		if(err){
			//出现错误交给下一个中间件
			next(err);
			return;
		}
		console.log(result);
        res.send({code:200,msg:'上传成功',data:result});
		});
})

//验证码(get /identify)
r.get("/identify",(req,res)=>{
	let code=randomCode(6);//生成6位数字随机验证码
	sendCode(req.query.phone,code,function(success){
	  console.log(req.query.phone);
	  console.log(success);
		if(success){
			res.send({code:200,msg:"短信验证码已发送",data:code});
		}else{
			res.send({code:201,msg:"短信验证码发送失败"});
		}
	})
  })
module.exports=r;